package ru.inse.core.dao.dict.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import ru.inse.core.dao.AbstractDao;
import ru.inse.core.dao.DaoException;
import ru.inse.core.dao.dict.IPlaceDao;
import ru.inse.core.domain.dict.Place;

@Repository
public class PlaceDao
    extends AbstractDao<Place>
    implements IPlaceDao
{
    private static final PlaceMapper PLACE_MAPPER = new PlaceMapper();

    @Transactional(readOnly = true)
    public Place getById(Long id)
    {
        return getJdbcTemplate().queryForObject("select * from place where id = ?", PLACE_MAPPER,
            new Object[]
            {
                id
            });
    }

    @Override
    @Transactional(readOnly = false)
    public void save(Place entity)
        throws DaoException
    {
        if (entity.getId() == null)
        {
            throw new DaoException(DaoException.IDS_ID_IS_NULL);
        }
        getJdbcTemplate().update("update place set name = ?, place_type_id = ?, city_id = ?  where id = ?", entity.getName(),
            entity.getType().getId(),
            entity.getCityId(),
            entity.getId());
    }

    @Override
    @Transactional(readOnly = false)
    public void persist(final Place entity)
        throws DaoException
    {
        if (entity.getId() != null)
        {
            throw new DaoException(DaoException.IDS_ID_IS_NOT_NULL);
        }
        KeyHolder keyHolder = new GeneratedKeyHolder();
        getJdbcTemplate().update(new PreparedStatementCreator()
        {
            public PreparedStatement createPreparedStatement(Connection connection)
                throws SQLException
            {
                PreparedStatement ps = connection.prepareStatement("insert into place (name, place_type_id, city_id) values (?,?,?)", new String[]{"ID"});
                ps.setString(1, entity.getName());
                ps.setLong(2, entity.getType().getId());
                ps.setLong(3, entity.getCityId());
                return ps;
            }
        }, keyHolder);
        entity.setId(keyHolder.getKey().longValue());
    }

    @Override
    @Transactional(readOnly = true)
    public List<Place> getAll()
    {
        return getJdbcTemplate().query("select * from place", PLACE_MAPPER);
    }
    
    @Override
    public String getTableName()
    {
        return "place";
    }
}
